<template>
    
    <div class="category">
        <!-- 左侧边栏-一级分类渲染 -->
        <van-sidebar v-model="active" @change="handleChange">
            <van-sidebar-item
            v-for="item in categories"
            :key="item.id"
            :title="item.name" 
            />
        </van-sidebar>
        <!-- 右侧宫格-二级分类渲染 -->
        <div class="category-right">
            <van-grid :column-num="3" clickable :icon-size="32" square>
                <van-grid-item 
                v-for="sub in subCategories" 
                :key="sub.id" 
                :text="sub.title" 
                >
                <template #icon>
                    <van-image :src="sub.imageUrl"  width="60" height="60">
                        <template v-slot:error>
                            <van-icon name="photo-fail"  size="50"/>
                        </template>
                    </van-image>
                </template>
                </van-grid-item>
            </van-grid>
        </div>


    </div>
</template>

<script>
import { getCategories,getSubCategories } from '../../api/category';
export default {
    name: 'Category',
    data() {
        return {
            active: 0,
            categories:[], //所有主分类
            subCategories:[],  //子分类数组,会根据不同的主分类切换来动态修改该数组
        }
    },
    created(){
        this.findAllCategories()
        
    },
    methods:{
        /**
         * 查找所有主分类数据
         */
        async findAllCategories(){
            const result = await getCategories()
            // console.log(result);
            this.categories = result.list.slice(1)

            //给子分类一个初始化的默认值
            this.handleChange(0)
        },

        /**
         * 切换某主分类下的子分类数据渲染
         */
        async handleChange(index){
            // 判断当前切换到的主分类下是否有其子分类数据存在，如果有，则直接使用
            if(this.categories[index].children){
                this.subCategories = this.categories[index].children
                return
            }
            // console.log(this.categories);
            // console.log(this.categories[index]);
            // console.log(this.categories[index].children);
            // 获取当前切换到的主分类 id
            const id = this.categories[index].id
            //等价于解构赋值
            //const {id} = this.categories[index]
            //根据主分类id查询子分类数据
            const result = await getSubCategories(id)
            this.subCategories = result.categories
            // 将查询到的子分类数据缓存保存到对应主分类下的 children 属性中
            this.categories[index].children = result.categories
        }
    }
}
</script>

<style lang="scss" scoped>
.category {
    display: flex;
    height: 100%;
    &-right {
        flex: 1;
        background-color: #f5f5f5;
        height: 100%;
    }

    // --van-grid-item-icon-size:80;
    // --van-grid-item-text-color:red;
    // --van-image-error-icon-size:60;
}



</style>
